package scanner;

import java.io.IOException;
import java.io.Reader;

public class PushBackQueue {
	
    private static final int INITIAL_BUFSIZE = 5;

    public static int[] resizeArray(int[] arrayToResize) {
       // create a new array twice the size
       int newCapacity = arrayToResize.length * 2;
       int[] newArray = new int[newCapacity];

       System.arraycopy(arrayToResize, 0,
          newArray, 0, arrayToResize.length);
       return newArray;
    }

    private Reader reader;
    private int[] buffer = new int[INITIAL_BUFSIZE];
    private int index = 0;

    public PushBackQueue(Reader r)
    {
        reader = r;
    }

    public int read() throws IOException
    {
        if (index > 0)
        {
            index--;
            return buffer[index];
        }

        return reader.read();
    }

    public void pushBack(int c)
    {
        if(index >= buffer.length) {
            buffer = resizeArray(buffer);
        }
        buffer[index++] = c;
    }

    /*
     * Pushes back an int array, ordered as it was received, into the buffer.
     */
    public void pushBack(int[] c)
    {
        for (int i = c.length -1; i>=0; i--)
            pushBack(c[i]);
    }
}
